#include "RunLengthDecoder.h"
#include <iostream>

RunLengthDecoder::RunLengthDecoder(): zeroCounter(-1)
{
}


RunLengthDecoder::~RunLengthDecoder()
{
}

unsigned int RunLengthDecoder::Read(void *data, unsigned int size)
{
	unsigned char *byteData = (unsigned char*)data;
	unsigned int totalread = 0;

	while(size--)
	{
		int byte = ReadNextByte();

		if (byte < 0)
			break;
		*byteData++ = byte;
		totalread++;
	}

	return totalread;
}

int RunLengthDecoder::ReadNextByte()
{
	unsigned char byte;

	if (zeroCounter < 0)
	{
		zeroCounter = 0;
		do
		{
			if (BufferedByteStream::Read(&byte, 1) == 0)
				return -1;

			zeroCounter += byte;
		}	
		while(byte == 255);

		if (BufferedByteStream::Read(&byte, 1) == 0)
			value = -1;
		else
			value = byte;
	}


	if (zeroCounter > 0)
	{
		zeroCounter--;

		return 0;
	}
	else
	{
		zeroCounter--;

		return value;
	}
}
